package com.yj.consumer.table;

import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class PageTableArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        Class<? extends MethodParameter> aClass = methodParameter.getClass();
        boolean assignableFrom = aClass.isAssignableFrom(PageTableRequest.class);
        if (assignableFrom){
            return true;
        }
        return false;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        HttpServletRequest request = (HttpServletRequest) nativeWebRequest.getNativeRequest();
        String current = request.getParameter("current");
        String limit = request.getParameter("limit");
        PageTableRequest pageTableRequest = new PageTableRequest();
        pageTableRequest.setOffset(Integer.parseInt(current));
        pageTableRequest.setLimit(Integer.parseInt(limit));
        Map<String, String[]> parameterMap = request.getParameterMap();
        HashMap<String, Object> map = new HashMap<>();

        parameterMap.forEach((k,v)->{
            if (v.length==1){
                map.put(k,v[0]);
            }else {
                map.put(k, Arrays.asList(v));
            }
        });
        pageTableRequest.setParams(map);


        return pageTableRequest;
    }
}
